package cn.swenty.backstage.base.web.system.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.swenty.backstage.base.web.system.entity.SysDepFormMap;
import cn.swenty.backstage.base.web.system.entity.SysRoleFormMap;
import cn.swenty.backstage.base.web.system.entity.SysUserFormMap;
import cn.swenty.backstage.base.web.system.entity.SysUserRoleFormMap;
import cn.swenty.backstage.base.web.system.model.Dept;
import cn.swenty.backstage.base.web.system.service.DepartService;
import cn.swenty.backstage.base.web.system.service.RoleService;
import cn.swenty.backstage.base.web.system.service.UserInfoService;
import cn.swenty.backstage.framework.common.tree.TreeNode;
import cn.swenty.backstage.framework.common.util.StringUtil;
import cn.swenty.backstage.framework.controller.BaseController;
import cn.swenty.backstage.framework.database.entity.Entity;
import cn.swenty.backstage.framework.database.plugin.PageView;
import cn.swenty.backstage.framework.util.Common;
import cn.swenty.backstage.framework.util.JsonUtils;
import cn.swenty.backstage.framework.util.POIUtils;
import cn.swenty.backstage.framework.util.PasswordHelper;

/**
 * 用户模块
 * @author liukang
 *
 */
@Controller
@RequestMapping("/system/userInfo/")
public class UserInfoController extends BaseController{
	
	@Inject
	private UserInfoService userInfoService;
	
	@Inject
	private DepartService departService;
	
	
	@Autowired
	private RoleService roleService;
	
	
	
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		String checkValueId = "";
		String checkValueName = "";
		List<Dept> depts = departService.findDeptTree();
		String hiddens = departService.findHiddens();
		//获取根节点下第一个子节点数据
		if(depts!=null&&depts.size()>0){
			checkValueId = depts.get(0).getId();
			checkValueName = depts.get(0).getName();
			
			//根节点下的子节点
			List<TreeNode> childrens = depts.get(0).getChildren();
			
			if(childrens!=null&&childrens.size()>0){
				for(int i=0;i<childrens.size();i++){
					TreeNode node = childrens.get(i);
					if(hiddens.indexOf(node.getId())==-1){
						checkValueId = node.getId();
						checkValueName = node.getName();
						break;
					}
				}
			}
		}
		getHttpRequest().setAttribute("hiddenDeptTree", hiddens);
		getHttpRequest().setAttribute("checkValueId",checkValueId);
		getHttpRequest().setAttribute("checkValueName",checkValueName);
		getHttpRequest().setAttribute("list",depts);
		return Common.BACKGROUND_PATH + "/system/user/list";
	}
	
	
	
	
	@RequestMapping("tree")
	public String tree() throws Exception{
		
		return webRoot+"/system/user/deptsTree";
	}
	
	
	
	/**
	 * 查询当前部门下用户
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("findUserByDeptId")
	public PageView findUserByDeptId(String pageNow,
			String pageSize,String column,String sort) {
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		if(StringUtil.isNull(sysUserFormMap.getStr("orderby"))){
			sysUserFormMap.put("orderby", " order by sequence ");
			column = "sequence";
			sort = "asc";
		}
		sysUserFormMap=toFormMap(sysUserFormMap, pageNow, pageSize,sysUserFormMap.getStr("orderby"));
		sysUserFormMap.put("column", column);
		sysUserFormMap.put("sort", sort);
		String dept_id=getPara("deptId");
		if(Common.isNotEmpty(dept_id)){
			sysUserFormMap.put("dept_id", dept_id);
		}
		String state =(String) sysUserFormMap.get("state");
		if(state==null)
			sysUserFormMap.put("state", 0);   //查在职
		else if(state.equals("2")){
			sysUserFormMap.remove("state");
		}
		
        pageView.setRecords(userInfoService.findUserByDeptId(sysUserFormMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	
	
	
	
	
	
	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage( String pageNow,
			String pageSize,String column,String sort) throws Exception {
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		if(StringUtil.isNull(sysUserFormMap.getStr("orderby"))){
			sysUserFormMap.put("orderby","order by sequence");			
		}
		sysUserFormMap=toFormMap(sysUserFormMap, pageNow, pageSize,sysUserFormMap.getStr("orderby"));
		sysUserFormMap.put("column", column);
		sysUserFormMap.put("sort", sort);
		String state =(String) sysUserFormMap.get("state");
		
		if(state==null)
			sysUserFormMap.put("state", 0);   //查在职
		else if(state.equals("2")){
			sysUserFormMap.put("state", null);   //默认全讯全部
		}
		String dept_id=getPara("deptId");
		if(Common.isNotEmpty(dept_id)){
			sysUserFormMap.put("dept_id", dept_id);
		}
        pageView.setRecords(userInfoService.findUserPage(sysUserFormMap));//不调用默认分页,调用自已的mapper中findUserPage
        return pageView;
	}
	
	@RequestMapping("/export")
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "用户列表";
		SysUserFormMap sysUserFormMap = findHasHMap(SysUserFormMap.class);
		//exportData = 
		// [{"colkey":"sql_info","name":"SQL语句","hide":false},
		// {"colkey":"total_time","name":"总响应时长","hide":false},
		// {"colkey":"avg_time","name":"平均响应时长","hide":false},
		// {"colkey":"record_time","name":"记录时间","hide":false},
		// {"colkey":"call_count","name":"请求次数","hide":false}
		// ]
		String exportData = sysUserFormMap.getStr("exportData");// 列表头的json字符串

		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);

		List<SysUserFormMap> lis =userInfoService.findUserPage(sysUserFormMap);
		POIUtils.exportToExcel(response, listMap, lis, fileName);

	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		String deptName=getPara("deptName");
		String deptId=getPara("deptId");
		getHttpRequest().setAttribute("deptName", deptName);
		getHttpRequest().setAttribute("deptId", deptId);
		getHttpRequest().setAttribute("hiddenDeptTree", departService.findHiddens());
		getHttpRequest().setAttribute("depts", departService.findDeptTree());
		return Common.BACKGROUND_PATH + "/system/user/info";
	}
	
	

	@ResponseBody
	@RequestMapping("addEntity")
	public String addEntity(){
			SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
			userInfoService.addEntity(sysUserFormMap);//新增后返回新增信息
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")   //逻辑删除
	public String deleteEntity() throws Exception {
			String ids = getPara("ids");
		
			if(!ids.isEmpty()){
				//用户表
				SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
				sysUserFormMap.put("state", 1);
				sysUserFormMap.put("user_id", ids.split(","));
				userInfoService.editEntits(sysUserFormMap);
				//用户角色中间表
				//userMapper.deleteByAttribute("user_id", id, SysUserRoleFormMap.class);
			}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String userId = getPara("userId");
		if(Common.isNotEmpty(userId)){
			
			SysUserFormMap sysUserFormMap = userInfoService.get(SysUserFormMap.class, userId);
			model.addAttribute("user",sysUserFormMap);
			String leaderId= (String) sysUserFormMap.get("leader_id");
			if(Common.isNotEmpty(leaderId)){
				SysUserFormMap leaderBean =userInfoService.get(SysUserFormMap.class, leaderId);
				model.addAttribute("leaderBean",leaderBean);
			}
			SysDepFormMap depFormMap = departService.get(SysDepFormMap.class, sysUserFormMap.get("dept_id"));
			if(depFormMap!=null){
				model.addAttribute("deptName",depFormMap.get("dept_name"));
				model.addAttribute("deptId",depFormMap.get("dept_id"));
			}
			getHttpRequest().setAttribute("hiddenDeptTree", departService.findHiddens());
			getHttpRequest().setAttribute("depts", departService.findDeptTree());
		}
		return Common.BACKGROUND_PATH + "/system/user/info";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String editEntity(Model model) throws Exception {
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		userInfoService.editEntit(sysUserFormMap);
		return "success";
	}
	

	
	/**
	 * 验证账号是否存在
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2014-2-19
	 * @param name
	 * @return
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name) {
		SysUserFormMap formMap = new SysUserFormMap();
		formMap.put("user_account",name);
		Entity user_account = formMap.queryOne();
		if (user_account == null) {
			return true;
		} else {
			return false;
		}
	}
	
	
	
	//保存新密码
	@RequestMapping("resetPwd")
	@ResponseBody
	public String resetPwd() throws Exception{
		//String [] userId =getParaValues("ids");
		//String id=Common.stringSplit(userIds);
		String  userIds =getPara("ids");
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		sysUserFormMap.set("password","888888");
		String password = PasswordHelper.encryptPassword((String)sysUserFormMap.get("password"));
		sysUserFormMap.put("password",password);
		sysUserFormMap.set("$in_user_id",userIds.split(","));
		sysUserFormMap.update();
		return "success";
	}
	
	
	
	/**
	 * 跳转到关联角色界面
	 * 
	 * @return
	 */
	@RequestMapping("roleUI")
	public String roleUI(Model model) {
		String userId = getPara("userId");
		SysUserRoleFormMap  sysUserRoleFormMap = getFormMap(SysUserRoleFormMap.class);
		sysUserRoleFormMap.put("where", " where user_id = "+"'"+userId+"'");
		//已有角色
		List<SysUserRoleFormMap>  roles =userInfoService.queryList(sysUserRoleFormMap);
		//所有角色
		 SysRoleFormMap formMap = new SysRoleFormMap();
		 formMap.put("column", "sequence");
		 List<SysRoleFormMap> list =  roleService.findRolePage(formMap);
		 model.addAttribute("list", list);
		 model.addAttribute("listRoleId", roles);
		 model.addAttribute("userId", userId);
		return Common.BACKGROUND_PATH + "/system/user/userRoleList";
	}
	
	
	
	
	/**
	 * 角色权限中间表
	 * @return
	 */
	@ResponseBody
	@RequestMapping("addUserRoleEntity")
	public String addUserRoleEntity(Model model){
			String []  roleIds = getParaValues("role_id");
			List<String>  list =Arrays.asList(roleIds);
			try {
				userInfoService.saveUserRole(list, getPara("userId"));
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
	}
	
	@ResponseBody
	@RequestMapping("updatePassword")
	public String updatePassword(){
		
		SysUserFormMap sysUserFormMap = getFormMap(SysUserFormMap.class);
		sysUserFormMap.set("user_id", getUser().getUserId());
		sysUserFormMap.put("password", getPara("password"));
		//这里对修改的密码进行加密
		String password = PasswordHelper.encryptPassword((String)sysUserFormMap.get("password"));
		sysUserFormMap.put("password",password);
		sysUserFormMap.put("enterprise_qq",  getPara("enterprise_qq"));
		userInfoService.updateField(SysUserFormMap.class, sysUserFormMap);
		Map<String, String> map = new HashMap<String, String>();
		map.put("a", "1");
		return "1";
	}
	
}
